package name.matthewgreet.example7.action; import org.apache.struts2.ActionSupport; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Actions; import org.apache.struts2.convention.annotation.InterceptorRef; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import org.apache.struts2.interceptor.validation.SkipValidation; import com.opensymphony.xwork2.validator.annotations.ConversionErrorFieldValidator; import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator; import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator; /** * Tests Struts 2 automatic type conversion for integers. */ @InterceptorRef("defaultStack") @Results({ @Result(name=ActionSupport.ERROR, location="/pages/ArithmeticEmbeddedForm.jsp"), @Result(name=ActionSupport.INPUT, location="/pages/ArithmeticEmbeddedForm.jsp"), @Result(name=ActionSupport.SUCCESS, location="/pages/ArithmeticEmbeddedForm.jsp") }) public class ArithmeticEmbeddedFormAction extends ActionSupport { private static final long serialVersionUID = -6084392315736424463L; private int operand1; private String operator; private Integer operand2; private String resultText; @Actions({ @Action("/"), @Action("/ArithmeticEmbeddedForm") }) @Override @SkipValidation public String execute() throws Exception { return SUCCESS; } @Action("/ArithmeticEmbeddedForm_submit") public String submit() throws Exception { try { int result; if (operand2 != null) { switch (operator) { case "+": result = operand1 + operand2; break; case "-": result = operand1 - operand2; break; case "/": result = operand1 / operand2; break; case "*": result = operand1 * operand2; break; default: result = 0; break; } resultText = operand1 + " " + operator + " " + operand2 + " = " + result; } else { resultText = "Operand 2 not set"; } return SUCCESS; } catch (Exception e) { System.out.println("Action failed reason=" + e.getMessage()); return ERROR; } } @ConversionErrorFieldValidator(message = "Operand 1 must be a number", repopulateField = true, shortCircuit = true) @RequiredFieldValidator(message = "Operand 1 is required") public int getOperand1() { return operand1; } public void setOperand1(int operand1) { this.operand1 = operand1; } @RequiredStringValidator(message = "Operator is required") public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } @ConversionErrorFieldValidator(message = "Operand 2 must be a number", repopulateField = true, shortCircuit = true) @RequiredFieldValidator(message = "Operand 2 is required") public Integer getOperand2() { return operand2; } public void setOperand2(Integer operand2) { this.operand2 = operand2; } public String getResultText() { return resultText; } }